package com.gxa.admin.recycling.service.impl;

import com.gxa.admin.recycling.mapper.GoodsMapper;
import com.gxa.admin.recycling.repository.GoodsRepository;
import com.gxa.admin.recycling.repository.ImgsRepository;
import com.gxa.admin.recycling.service.GoodsService;
import com.gxa.core.recycling.pojo.Goods;
import com.gxa.core.recycling.pojo.Imgs;
import com.gxa.core.recycling.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements GoodsService  {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    ImgsRepository imgsRepository;
    @Override
    public List<Map> findAllByPage(Long id, String name, String type, Boolean hot, Integer page, Integer size) {
        if (name!=null && name !=""){
            name = "%"+name+"%";
        }
        List<Map> allByPage = goodsMapper.findAllByPage(id, name, type, hot, (page - 1) * size, size);
        List<Map> fine = new ArrayList<>();
        j:for (Map map : allByPage) {
            for (Map map1 : fine) {
                if (map.get("id").equals(map1.get("id"))){
                    continue j;
                }
            }
            fine.add(map);
        }
        return fine;
    }

    @Override
    public Goods findByName(String name) {
        return goodsMapper.findByName(name);
    }

    @Override
    public void addGoodsToMongo(Goods goods) {
        goodsRepository.save(goods);
    }

    @Override
    public void addImgsToMongo(Imgs imgs) {
        imgsRepository.save(imgs);
    }

    @Override
    public void updateMySqlAndMonge(Goods goods) {
        updateById(goods);
        if (goods.getState()){
            goodsRepository.deleteGoodsByIdEquals(goods.getId());
            Goods goods1 = selectById(goods.getId());
            goodsRepository.save(goods1);
        }else{
            goodsRepository.deleteGoodsByIdEquals(goods.getId());
        }
    }
}
